<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\SystemConfig\Action\Admin;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Utils\Url;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;
use MoChat\Plugin\SystemConfig\Contract\SystemConfigContract;

/**
 * 系统管理-列表
 * Class Index.
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SystemConfigContract
     */
    protected $systemConfigService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/admin/systemConfig/index", methods="get")
     * @throws \JsonException
     */
    public function handle(): array
    {
        $user = user();
        // 验证参数
        $this->validated($this->request->all());
        // 接收参数
        $type = $this->request->input('type');
        // OEM信息配置
        if ($type === 'oem') {
            return ['urlDomain' => Url::getApiBaseUrl() . '/static/', 'list' => $this->getOemConfig()];
        }
        // OSS信息配置
        if ($type === 'oss') {
            return ['urlDomain' => Url::getApiBaseUrl() . '/static/', 'list' => $this->getOssConfig()];
        }
        // 微信信息配置
        if ($type === 'wechat') {
            return ['urlDomain' => Url::getApiBaseUrl() . '/static/', 'list' => $this->getWechatConfig()];
        }
        // 系统版本配置
        if ($type === 'version') {
            return ['urlDomain' => Url::getApiBaseUrl() . '/static/', 'list' => $this->getVersionConfig()];
        }
        return [];
    }

    protected function getOemConfig(): array
    {
        $names = ['oem.domain', 'oem.site_title', 'oem.site_keyword', 'oem.site_description', 'oem.dashboard_url', 'oem.api_url', 'oem.sidebar_url', 'oem.operation_url', 'oem.brand_name', 'oem.login_logo', 'oem.mini_logo', 'oem.customer_service_qrcode', 'oem.right_title', 'oem.right_version', 'oem.right_description', 'oem.copyright_name', 'oem.copyright_url', 'oem.icp', 'oem.ico', 'oem.qrcode_register', 'oem.validation_code_login', 'oem.mobile_register'];
        $oemConfig = $this->getConfigValues($names);
        if (empty($oemConfig)) {
            return $oemConfig;
        }

        foreach ($oemConfig as &$item) {
            $uploadNames = $this->getUploadOemNames();
            if (in_array($item['name'], $uploadNames)) {
                $item['fullValue'] = file_full_url($item['value']);
            }
        }

        return $oemConfig;
    }

    protected function getOssConfig(): array
    {
        $names = ['storage.type', 'storage.local.scheme', 'storage.local.domain', 'storage.qiniu.scheme', 'storage.qiniu.domain', 'storage.qiniu.bucket', 'storage.qiniu.access_key', 'storage.qiniu.secret_key', 'storage.oss.scheme', 'storage.oss.domain', 'storage.oss.bucket', 'storage.oss.endpoint', 'storage.oss.accessId', 'storage.oss.accessSecret', 'storage.cos.scheme', 'storage.cos.domain', 'storage.cos.bucket', 'storage.cos.region', 'storage.cos.app_id', 'storage.cos.secret_id', 'storage.cos.secret_key '];
        return $this->getConfigValues($names);
    }

    protected function getWechatConfig(): array
    {
        $names = ['wechat.official_account.auth_mode', 'wechat.open_platform.app_id', 'wechat.open_platform.secret', 'wechat.open_platform.token', 'wechat.open_platform.aes_key'];
        return $this->getConfigValues($names);
    }

    protected function getVersionConfig(): array
    {
        $names = ['oem.right_title', 'oem.right_version', 'oem.right_description'];
        return $this->getConfigValues($names);
    }

    protected function getConfigValues($names): array
    {
        $config = $this->systemConfigService->getSystemConfigsByName($names, ['id', 'name', 'remark']);
        foreach ($config as $k => $v) {
            $config[$k]['value'] = '';
            $config[$k]['description'] = '';
            $configValue = $this->systemConfigService->getSystemConfigValueByConfigId($v['id'], ['value', 'description']);
            if (! empty($configValue)) {
                $config[$k]['value'] = $configValue['value'];
                $config[$k]['description'] = $configValue['description'];
            }
        }
        return $this->arraySort($config, 'id', 'asc');
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.required' => 'type 必传',
        ];
    }

    /**
     * 二维数组排列.
     * @param $array
     * @param $keys
     * @return array
     */
    private function arraySort($array, $keys, string $sort = 'asc')
    {
        $newArr = $valArr = [];
        foreach ($array as $key => $value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort === 'asc') ? asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach ($valArr as $key => $value) {
            $newArr[$key] = $array[$key];
        }
        return array_merge($newArr);
    }

    private function getUploadOemNames()
    {
        return [
            'oem.login_logo', 'oem.mini_logo', 'oem.customer_service_qrcode', 'oem.ico',
        ];
    }
}
